package br.com.andre.neo4j.model;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction; 
import org.neo4j.graphdb.index.Index;

public class MovieDAO {
	
	private Connection conn;
	
	public MovieDAO() {
		this.conn = new Connection();
	}
	
	public void createMovieIndex (MovieTO movie){
		GraphDatabaseService graph = conn.newConnection();
		Index<Node> index = graph.index().forNodes("movie");
		Node node = index.get("title", movie.getTitle()).getSingle();
		if (node == null) {
			Transaction tx = graph.beginTx();
			try {
				node = graph.createNode();
				node.setProperty("title", movie.getTitle());
				node.setProperty("year", movie.getYear());
				index.add(node, "title", movie.getTitle());
				
				tx.success();
				System.out.println("movie saved!");
			} catch (Exception e) {
				tx.failure();
			} finally{
				tx.finish();
			
			}
			
		} else {
			System.out.println("The movie has already been registered!");
		}
		graph.shutdown();
	}

}
